package requestshandler;

import java.util.ArrayList;
import java.util.List;

import org.joda.time.DateTime;

import util.MailSender;
import books.Loan;

public class OverduedLoansNotifier {

    // ---------INSTANCE VARIABLES-----------------------------------------//

    private MailSender mailSender;

    private History history;

    // ---------CONSTRUCTORS------------------------------------------------//

    public MailSender getMailSender() {
        return this.mailSender;
    }

    public void setMailSender(final MailSender mailSender) {
        this.mailSender = mailSender;
    }

    public History getHistory() {
        return this.history;
    }

    public void setHistory(final History history) {
        this.history = history;
    }

    public OverduedLoansNotifier(final History aHistory) {
        this.history = aHistory;
        this.mailSender = new MailSender();
    }

    // ---------OTHER BEHAVIOUR---------------------------------------------//

    private List<Loan> checkForOverduedLoaners() {
        List<Loan> overdued = new ArrayList<Loan>();
        List<Loan> actualLoans = this.history.getActualLoans();
        int today = DateTime.now().getDayOfYear();

        for (Loan it : actualLoans) {

            if (it.getEnd().getDayOfYear() < today) {
                overdued.add(it);
            }
        }

        return overdued;
    }

    public void sendMailsToOverduedLoaners() {
        List<Loan> overduedLoans = this.checkForOverduedLoaners();
        String subjectOfOutgoingMail = "URGENTE - Biblioteca";

        for (Loan it : overduedLoans) {
            String head = "Estimado usuario " + it.getLoaner().getName() + it.getLoaner().getSurname();
            String body = "Por medio de este correo le recordamos que se encuentra en deuda del" + "libro "
                    + it.getLoanedBook().getInfo().getTitle() + " que usted retiro el dia " + it.getStart().toString()
                    + " de nuestra Biblioteca." + "DEBERIA HABERLO DEVUELTO EL DIA" + it.getEnd().toString();
            String end = "Le instamos a que lo devuelva a la brevedad, para evitar penalidades mas graves";
            String sign = "Biblioteca para Todos";

            this.mailSender.sendMail(it.getLoaner().getMail(), subjectOfOutgoingMail, head + body + end + sign);
        }
    }

}
